<?php
include_once 'library/Bootstrap/Bootstrap.php';
class ApplicationBootstrap implements Bootstrap{

	/**
	 * List Route
	 * @var Route[]
	 */
	private $_routes;

	public function __construct(){
		$this->_init();
	}
	/**
	 * (non-PHPdoc)
	 * @see library/Bootstrap/Bootstrap::_init()
	 */
	public function _init(){}
	/**
	 * (non-PHPdoc)
	 * @see library/Bootstrap/Bootstrap::addRoute()
	 * @param Route $route
	 */
	public function addRoute($route){
		if(!isset($this->_routes[$route->getName()])){
			$this->_routes[$route->getName()] = $route;
		}
		else{
			$msg = "Route " . $route->getName() . " exist in route list";
			Log::error("ApplicationBootstrap", $msg);
			if(Configuration::DEBUG_MOD)
			throw new BoostrapException($msg);
		}
	}
	/**
	 * (non-PHPdoc)
	 * @see library/Bootstrap/Bootstrap::getRoute()
	 * @return string URL matched or input url if not match.
	 */
	public function getRoute(){
		return $this->_routes;
	}
	/**
	 * (non-PHPdoc)
	 * @see library/Bootstrap/Bootstrap::run()
	 * @return Route
	 * @param HttpContext $context
	 */
	public function run($context = null){
		$route = $this->routeModule($context);
		if(!isset($route[Configuration::MODULE])) $route[Configuration::MODULE] = Configuration::MODULE_DEFAULT;
		$bootstrap = BootstrapFactory::instance($route[Configuration::MODULE]);
		$bootstrap->context = $context;
		$bootstrap->moduleRoute = $route;
		$bootstrap->run();
	}
	/**
	 * Redirect to module ...
	 * @param HttpContext $context
	 */
	private function routeModule($context){
		if($context->getRedirectUrl() != STRING_EMPTY){
			foreach ($this->_routes as $value) {
				$r_result = $value->match($context->getRedirectUrl());
				if($r_result[Route::ROUTE_ISMATCH] == Route::ROUTE_MATCH){
					$urlstr = $r_result[Route::ROUTE_URL];
					parse_str($urlstr,$output);
					$output[Route::ROUTE_QUERY] = $context->getQueryString();
					return $output;
				}
			}
			return array(
			Configuration::MODULE => Configuration::MODULE_DEFAULT,
			Route::ROUTE_URL => $context->getRedirectUrl(),
			Route::ROUTE_QUERY =>$context->getQueryString()
			);
		}
		else{
			if($context->getQueryString() != STRING_EMPTY){
				parse_str($context->getQueryString(),$output);
				$output[Route::ROUTE_URL] = STRING_EMPTY;
				$output[Route::ROUTE_QUERY] = $context->getQueryString();
				return $output;
			}
			else{
				return array(
				Configuration::MODULE => Configuration::MODULE_DEFAULT,
				Route::ROUTE_URL => $context->getRedirectUrl(),
				Route::ROUTE_QUERY =>$context->getQueryString()
				);
			}
		}
	}
}